package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * Author: 笨蛋超人不会飞
 * Date:  22:50
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;
    //处理两个两个业务，一个是下单超过15min还没有支付的，对应的order数据库中的数据status状态为1，一个是处理前一天已完成但是还没有点击完成的订单（状态为4）
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单:{}",new Date());
        //获取15min之前的时间
        LocalDateTime time=LocalDateTime.now().plusMinutes(-15);
        //调用Mapper的查询接口
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, time);
        //看看是否有支付超时的订单
        if(ordersList!=null && ordersList.size()>0){
            //更新order了哦
            ordersList.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("支付超时");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);

            });
        }

    }
    //cron设置每天一点执行定时任务
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("半夜处理前一天正在派送中的订单：{}",new Date());
        //获取前一天的时间,刚好是前一天十二点
        LocalDateTime time=LocalDateTime.now().plusMinutes(-60);
        //调用Mapper的查询接口
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS,time);
        if (ordersList!=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }


}
